<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use fast\Random;
use think\Db;
use app\common\model\User as Users;
/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;

    /**
     * User模型对象
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with('group')
                    ->where($where)
                    ->order($sort, $order)
                    ->count();
            $list = $this->model
                    ->with('group')
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            foreach ($list as $k => $v)
            {
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
/**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = Users::get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if($params['password']){
                    $salt = Random::alnum();
                    $newpassword = $this->getEncryptPassword($params['password'], $salt);
                    $params['channelname'] = $params['password'] = $newpassword;
                    $params['salt'] = $salt;
                }else{
                    unset($params['password']);
                }
                try {
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
       $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    /**
   
     /**
     * 添加
     */
    public function add()
    {
         if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                 // 检测用户名或邮箱、手机号是否存在
                if (Users::getByUsername($params['username']))
                {
                    $this->error('用户名已经存在');
                }
                if (Users::getByMobile($params['mobile']))
                {
                    $this->error('手机号已经存在');
                }
                $ip = request()->ip();
                $time = time();
                $data = array_merge($params, [
                    'salt'      => Random::alnum(),
                    'jointime'  => $time,
                    'joinip'    => $ip,
                    'logintime' => $time,
                    'loginip'   => $ip,
                    'prevtime'  => $time,
                    'status'    => 'normal'
                ]);
                $data['channelname'] = $data['password'] = $this->getEncryptPassword($data['password'], $data['salt']);
                 //账号注册时需要开启事务,避免出现垃圾数据
                Db::startTrans();
                try {
                     $result = Users::create($data);
                    if ($result !== false) {
                        Db::commit();
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
        }

    $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), 0, ['class' => 'form-control selectpicker']));
    return $this->view->fetch();
    }
     /**
     * 获取密码加密后的字符串
     * @param string $password  密码
     * @param string $salt      密码盐
     * @return string
     */
    public function getEncryptPassword($password, $salt = '')
    {
        return md5(md5($password) . $salt);
    }

}
